﻿using System.Windows;
using personalplaner.common.mvvm;
using personalplaner.business.stamm;
using System.Collections.Generic;
using personalplaner.servicemodel.dataaccess;
using System;
using System.Windows.Input;
using personalplaner.common.mvvm.commands;
using personalplaner.gui.common;
using System.Text;
using personalplaner.gui.stamm.windows;
using personalplaner.business.enums;
using personalplaner.gui.Properties;
using personalplaner.business;

namespace personalplaner.gui.plugins.dienstplan.viewmodels
{
	public class CreateNewPlanViewModel : BaseViewModel
	{
		public CreateNewPlanViewModel(DependencyObject parent)
			: base(parent)
		{
		}

		#region Implementation

		public override void Loaded()
		{
			var mw = GetService<IMainWindowDisplayContainer>();
			mw.IsWaitVisible = false;
		}

		private bool Save()
		{

			if (string.IsNullOrEmpty(Name) || SelectedMonth == null || SelectedLayout == null)
				return false;


			var da = GetService<IPlanDataAccess>();
			if (da.DoesPlanExist(SelectedMonth.AtId, SelectedLayout.SchemaID))
			{
				MessageBox.Show("In dem angegebenen Zeitraum existiert bereis ein Plan mit diesem Schema,\noder eine Abteilungen aus dem Schema wird bereits in dem angegebenen Zeitraum eingesetzt.", "Plan existiert bereits", MessageBoxButton.OK);
				return false;
			}

			//check if months have days set
			if (SelectedMonth.Tage <= 0)
			{
				var sb = new StringBuilder();
				sb.AppendLine("Diesem Monat wurde noch keine Anzahl an Arbeitstagen zugewiesen.");
				sb.AppendLine("Es muss eine Anzahl an Arbeitstagen angegeben werden damit die Berechnung der Arbeitsstunden korrekt funktioniert.");
				sb.AppendLine("Möchten Sie die Anzahl an Arbeitstagen jetzt angeben?");
				if (MessageBox.Show(Window.GetWindow(Parent),
					sb.ToString(),
					"Arbeitstage im Monat",
					MessageBoxButton.YesNo,
					MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
				{
					var dlg = new EditDaysInMonth()
					{
						Owner = Window.GetWindow(Parent)
					};

					var wnd = Parent as Window;
					if (wnd != null)
						wnd.Visibility = Visibility.Collapsed;

					dlg.SelectMonth(SelectedMonth.AtId);
					dlg.ShowDialog();

					if (wnd != null)
						wnd.Visibility = Visibility.Visible;
				}
			}

			var planId = da.CreateNewPlan(Name, SelectedMonth.AtId, SelectedLayout.SchemaID, !IsSpecificSchema);

			if (planId <= 0)
			{
				MessageBox.Show(Resources.ErrorOnCreatePlan, Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
				return false;
			}

			da.InitializeDienstSerie(planId);

			// select the corect main view
			var mp = GetService<IMainWindowDisplayContainer>();
			mp.SelectItem(enDisplayItemType.MainPlanView);

			// use mediator to notify all suscribed methods that a new plan was created
			Mediator.NotifyColleagues<int>("NewPlanAdded", planId);
			
			return true;
		}

		#endregion

		#region Commands

		ICommand _okcommand;
		public ICommand OkCommand
		{
			get
			{
				if (_okcommand == null)
					_okcommand = new RelayCommand(OnOkCommand, parameter => !string.IsNullOrEmpty(Name) && SelectedMonth != null && SelectedLayout != null);
				return _okcommand;
			}
		}

		private void OnOkCommand(object parameter)
		{
			if (!Save())
				return;

			var wnd = Parent as Window;
			if (wnd == null)
				throw new Exception();

			try
			{
				wnd.DialogResult = true;
			}
			catch (InvalidOperationException)
			{
			}

			wnd.Close();
		}

		ICommand _cancelcommand;
		public ICommand CancelCommand
		{
			get
			{
				if (_cancelcommand == null)
					_cancelcommand = new RelayCommand(OnCancelCommand);
				return _cancelcommand;
			}
		}

		private void OnCancelCommand(object parameter)
		{
			var wnd = Parent as Window;
			if (wnd == null)
				throw new Exception();

			try
			{
				wnd.DialogResult = false;
			}
			catch (InvalidOperationException)
			{
			}

			wnd.Close();
		}

		#endregion

		#region Properties

		string _name;
		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				_name = value;
				RaisePropertyChanged("Name");
			}
		}

		bool _isSpecificSchema;
		public bool IsSpecificSchema
		{
			get
			{
				return _isSpecificSchema;
			}
			set
			{
				_isSpecificSchema = value;
				RaisePropertyChanged("IsSpecificSchema");
			}
		}

		IList<PlanSchema> _planLayouts;
		public IList<PlanSchema> PlanLayouts
		{
			get
			{
				if (_planLayouts == null)
				{
					var da = GetService<IPlanSchemaDataAccess>();
					var lst = da.GetSchemas(false);
					_planLayouts = lst != null ? new List<PlanSchema>(lst) : new List<PlanSchema>();
				}

				if (_planLayouts != null && _planLayouts.Count > 0)
					SelectedLayout = _planLayouts[0];

				return _planLayouts;
			}
		}

		PlanSchema _selectedLayout;
		public PlanSchema SelectedLayout
		{
			get { return _selectedLayout; }
			set
			{
				_selectedLayout = value;
				RaisePropertyChanged("SelectedLayout");
			}
		}

		IList<PlanMonth> _monthList;
		public IList<PlanMonth> MonthList
		{
			get
			{
				if (_monthList == null)
				{
					var da = GetService<ICommonDataAccess>();
					var lst = da.GetActiveMonths();
					_monthList = lst != null ? new List<PlanMonth>(lst) : new List<PlanMonth>();
				}

				if (_monthList != null && _monthList.Count >= DateTime.Now.Month)
					SelectedMonth = _monthList[DateTime.Now.Month - 1];

				return _monthList;
			}
		}

		PlanMonth _selectedMonth;
		public PlanMonth SelectedMonth
		{
			get { return _selectedMonth; }
			set
			{
				_selectedMonth = value;
				RaisePropertyChanged("SelectedMonth");
			}
		}

		#endregion
	}
}
